'use strict';

let { Users } = require('../models');

let register_fn = async (ctx, next) => {
    ctx.render('register.html');
};

let regiser_judge_fn = async (ctx, next) => {
    let uid = ctx.request.body.username.trim();
    let pwd = ctx.request.body.password.trim();
    let repwd = ctx.request.body.repassword.trim();

    let res = '';

    if (pwd !== repwd) {
        res = { code: 400, msg: '两次密码不一致' };
    }else if(uid === "root" && pwd === "123456"){
        res = { code: 400, msg: '用户已存在' };
    }else {
        let user = await Users.findOne({ where: { username: uid } });
        if (!user) {

            let u1 = await Users.create({
                username: uid,
                password: pwd,
            });
            let u1Json = JSON.stringify(u1);
            if (u1Json !== 'null') {
                res = { code: 200 };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功' };
            }
        } else {
            res = { code: 400, msg: '用户已注册，请重新输入' };
        }

    }
    ctx.body = JSON.stringify(res);

};



module.exports = {
    '/register': ['get', register_fn],
    '/register/judge': ['post', regiser_judge_fn],
}